package cn.cht.listener;

import cn.cht.constant.ConmmonConstant;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;

@Slf4j
@Component
@RocketMQMessageListener(topic = ConmmonConstant.COMMODITY_MQ, consumerGroup = "cht")
public class OrderListener implements RocketMQListener<String> {

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 监听消费
     *
     * @param msg
     */
    @Override
    public void onMessage(String msg) {
        HashMap map = JSONUtil.toBean(msg, HashMap.class);
        String userId = (String) map.get("userId");
        String orderId = (String) map.get("orderId");
        Integer num = (Integer) map.get("num");
        log.info("用户:{},下单商品:{}:{}个", userId, orderId, num);
        if (ConmmonConstant.flag){
            //支付成功
            log.info("用户支付成功!扣减库存!");
            for (int i = 0; i < num; i++) {
                redisTemplate.opsForList().leftPop(ConmmonConstant.COMMODITY_KEY);
            }
        }else {
            //支付失败
            log.info("用户支付失败或者超时未支付,恢复库存");
            redisTemplate.opsForValue().increment(ConmmonConstant.ORDKER_KEY, 1 * num);

        }


    }

}
